package org.spring.batch.ch07;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.batch.ch05.model.Group;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemStreamException;

public class SynchronizingItemReader implements ItemReader<Group>, ItemStream {
	private ItemReader<Group> delegate;
	private Logger logger = LoggerFactory.getLogger(getClass());

	public synchronized Group read() throws Exception {
		Group group = delegate.read();
		if (group != null)
			logger.info("Thread:{}, readItem:{}", Thread.currentThread().getName(), group.getId());
		return group;
	}

	public ItemReader<Group> getDelegate() {
		return delegate;
	}

	public void setDelegate(ItemReader<Group> delegate) {
		this.delegate = delegate;
	}

	public void close() throws ItemStreamException {
		if (this.delegate instanceof ItemStream) {
			((ItemStream) this.delegate).close();
		}
	}

	public void open(ExecutionContext context) throws ItemStreamException {
		if (this.delegate instanceof ItemStream) {
			((ItemStream) this.delegate).open(context);
		}
	}

	public void update(ExecutionContext context) throws ItemStreamException {
		if (this.delegate instanceof ItemStream) {
			((ItemStream) this.delegate).update(context);
		}
	}

}
